package com.gujiangbo.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gujiangbo.constant.CommonsConstant;
import com.gujiangbo.request.BatchGenerateCondition;
import com.gujiangbo.request.SchoolmateRequest;
import com.gujiangbo.response.SchoolmateResponse;
import com.gujiangbo.service.SchoolmateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2021/12/7 20:40
 * @Version: 1.0
 * @Description:
 */
@RestController
@RequestMapping("/api")
@Api(tags = "同班同学")
@Slf4j
public class SchoolmateController {

    private final ObjectMapper mapper = new ObjectMapper();

    @Resource
    private SchoolmateService schoolmateService;

    @ApiOperation("批量生成同学信息")
    @RequestMapping(value = "/batchGenerateSchoolmates", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String batchGenerateSchoolmates(@RequestBody String requestBody) {
        String response = "batchGenerateSchoolmates success.";
        log.info("batchGenerateSchoolmates starts.");
        try {
            BatchGenerateCondition condition = mapper.readValue(requestBody, BatchGenerateCondition.class);
            StopWatch watch = new StopWatch("耗时开始");
            watch.start("batchGenerate start");
            schoolmateService.batchGenerateSchoolmates(condition);
            watch.stop();
            log.info(watch.prettyPrint());
        } catch (Exception e) {
            response = e.getMessage();
        }
        return response;
    }


    @ApiOperation("获取同学信息")
    @RequestMapping(value = {"/getSchoolmate"}, method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getSchoolmate(@RequestBody String requestBody) {
        log.info("getSchoolmate starts.");
        SchoolmateResponse schoolmate = new SchoolmateResponse();
        try {
            SchoolmateRequest request = mapper.readValue(requestBody, SchoolmateRequest.class);
            schoolmate = schoolmateService.getSchoolmate(request);
        } catch (Exception e) {
            schoolmate.setCode(CommonsConstant.FAIL_CODE);
            schoolmate.setMessage(CommonsConstant.FAIL_MSG + ":" + e.getMessage());
        }
        String msg = JSONObject.toJSONString(schoolmate);
        log.info("schoolmate msg:" + msg);
        return msg;
    }

}
